{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 门控循环单元（GRU）\n",
    ":label:`sec_gru`\n",
    "\n",
    "在 :numref:`sec_bptt`中，\n",
    "我们讨论了如何在循环神经网络中计算梯度，\n",
    "以及矩阵连续乘积可以导致梯度消失或梯度爆炸的问题。\n",
    "下面我们简单思考一下这种梯度异常在实践中的意义：\n",
    "\n",
    "* 我们可能会遇到这样的情况：早期观测值对预测所有未来观测值具有非常重要的意义。\n",
    "  考虑一个极端情况，其中第一个观测值包含一个校验和，\n",
    "  目标是在序列的末尾辨别校验和是否正确。\n",
    "  在这种情况下，第一个词元的影响至关重要。\n",
    "  我们希望有某些机制能够在一个记忆元里存储重要的早期信息。\n",
    "  如果没有这样的机制，我们将不得不给这个观测值指定一个非常大的梯度，\n",
    "  因为它会影响所有后续的观测值。\n",
    "* 我们可能会遇到这样的情况：一些词元没有相关的观测值。\n",
    "  例如，在对网页内容进行情感分析时，\n",
    "  可能有一些辅助HTML代码与网页传达的情绪无关。\n",
    "  我们希望有一些机制来*跳过*隐状态表示中的此类词元。\n",
    "* 我们可能会遇到这样的情况：序列的各个部分之间存在逻辑中断。\n",
    "  例如，书的章节之间可能会有过渡存在，\n",
    "  或者证券的熊市和牛市之间可能会有过渡存在。\n",
    "  在这种情况下，最好有一种方法来*重置*我们的内部状态表示。\n",
    "\n",
    "在学术界已经提出了许多方法来解决这类问题。\n",
    "其中最早的方法是\"长短期记忆\"（long-short-term memory，LSTM）\n",
    " :cite:`Hochreiter.Schmidhuber.1997`，\n",
    "我们将在 :numref:`sec_lstm`中讨论。\n",
    "门控循环单元（gated recurrent unit，GRU）\n",
    " :cite:`Cho.Van-Merrienboer.Bahdanau.ea.2014`\n",
    "是一个稍微简化的变体，通常能够提供同等的效果，\n",
    "并且计算 :cite:`Chung.Gulcehre.Cho.ea.2014`的速度明显更快。\n",
    "由于门控循环单元更简单，我们从它开始解读。\n",
    "\n",
    "## 门控隐状态\n",
    "\n",
    "门控循环单元与普通的循环神经网络之间的关键区别在于：\n",
    "后者支持隐状态的门控。\n",
    "这意味着模型有专门的机制来确定应该何时更新隐状态，\n",
    "以及应该何时重置隐状态。\n",
    "这些机制是可学习的，并且能够解决了上面列出的问题。\n",
    "例如，如果第一个词元非常重要，\n",
    "模型将学会在第一次观测之后不更新隐状态。\n",
    "同样，模型也可以学会跳过不相关的临时观测。\n",
    "最后，模型还将学会在需要的时候重置隐状态。\n",
    "下面我们将详细讨论各类门控。\n",
    "\n",
    "### 重置门和更新门\n",
    "\n",
    "我们首先介绍*重置门*（reset gate）和*更新门*（update gate）。\n",
    "我们把它们设计成$(0, 1)$区间中的向量，\n",
    "这样我们就可以进行凸组合。\n",
    "重置门允许我们控制“可能还想记住”的过去状态的数量；\n",
    "更新门将允许我们控制新状态中有多少个是旧状态的副本。\n",
    "\n",
    "我们从构造这些门控开始。 :numref:`fig_gru_1`\n",
    "描述了门控循环单元中的重置门和更新门的输入，\n",
    "输入是由当前时间步的输入和前一时间步的隐状态给出。\n",
    "两个门的输出是由使用sigmoid激活函数的两个全连接层给出。\n",
    "\n",
    "![在门控循环单元模型中计算重置门和更新门](https://d2l.ai/_images/gru-1.svg)\n",
    ":label:`fig_gru_1`\n",
    "\n",
    "我们来看一下门控循环单元的数学表达。\n",
    "对于给定的时间步$t$，假设输入是一个小批量\n",
    "$\\mathbf{X}_t \\in \\mathbb{R}^{n \\times d}$\n",
    "（样本个数：$n$，输入个数：$d$），\n",
    "上一个时间步的隐状态是\n",
    "$\\mathbf{H}_{t-1} \\in \\mathbb{R}^{n \\times h}$\n",
    "（隐藏单元个数：$h$）。\n",
    "那么，重置门$\\mathbf{R}_t \\in \\mathbb{R}^{n \\times h}$和\n",
    "更新门$\\mathbf{Z}_t \\in \\mathbb{R}^{n \\times h}$的计算如下所示：\n",
    "\n",
    "$$\n",
    "\\begin{aligned}\n",
    "\\mathbf{R}_t = \\sigma(\\mathbf{X}_t \\mathbf{W}_{xr} + \\mathbf{H}_{t-1} \\mathbf{W}_{hr} + \\mathbf{b}_r),\\\\\n",
    "\\mathbf{Z}_t = \\sigma(\\mathbf{X}_t \\mathbf{W}_{xz} + \\mathbf{H}_{t-1} \\mathbf{W}_{hz} + \\mathbf{b}_z),\n",
    "\\end{aligned}\n",
    "$$\n",
    "\n",
    "其中$\\mathbf{W}_{xr}, \\mathbf{W}_{xz} \\in \\mathbb{R}^{d \\times h}$\n",
    "和$\\mathbf{W}_{hr}, \\mathbf{W}_{hz} \\in \\mathbb{R}^{h \\times h}$是权重参数，\n",
    "$\\mathbf{b}_r, \\mathbf{b}_z \\in \\mathbb{R}^{1 \\times h}$是偏置参数。\n",
    "请注意，在求和过程中会触发广播机制\n",
    "（请参阅 :numref:`subsec_broadcasting`）。\n",
    "我们使用sigmoid函数（如 :numref:`sec_mlp`中介绍的）\n",
    "将输入值转换到区间$(0, 1)$。\n",
    "\n",
    "### 候选隐状态\n",
    "\n",
    "接下来，让我们将重置门$\\mathbf{R}_t$\n",
    "与 :eqref:`rnn_h_with_state`\n",
    "中的常规隐状态更新机制集成，\n",
    "得到在时间步$t$的*候选隐状态*（candidate hidden state）\n",
    "$\\tilde{\\mathbf{H}}_t \\in \\mathbb{R}^{n \\times h}$。\n",
    "\n",
    "$$\\tilde{\\mathbf{H}}_t = \\tanh(\\mathbf{X}_t \\mathbf{W}_{xh} + \\left(\\mathbf{R}_t \\odot \\mathbf{H}_{t-1}\\right) \\mathbf{W}_{hh} + \\mathbf{b}_h),$$\n",
    ":eqlabel:`gru_tilde_H`\n",
    "\n",
    "其中$\\mathbf{W}_{xh} \\in \\mathbb{R}^{d \\times h}$\n",
    "和$\\mathbf{W}_{hh} \\in \\mathbb{R}^{h \\times h}$是权重参数，\n",
    "$\\mathbf{b}_h \\in \\mathbb{R}^{1 \\times h}$是偏置项，\n",
    "符号$\\odot$是Hadamard积（按元素乘积）运算符。\n",
    "在这里，我们使用tanh非线性激活函数来确保候选隐状态中的值保持在区间$(-1, 1)$中。\n",
    "\n",
    "与 :eqref:`rnn_h_with_state`相比，\n",
    " :eqref:`gru_tilde_H`中的$\\mathbf{R}_t$和$\\mathbf{H}_{t-1}$\n",
    "的元素相乘可以减少以往状态的影响。\n",
    "每当重置门$\\mathbf{R}_t$中的项接近$1$时，\n",
    "我们恢复一个如 :eqref:`rnn_h_with_state`中的普通的循环神经网络。\n",
    "对于重置门$\\mathbf{R}_t$中所有接近$0$的项，\n",
    "候选隐状态是以$\\mathbf{X}_t$作为输入的多层感知机的结果。\n",
    "因此，任何预先存在的隐状态都会被*重置*为默认值。\n",
    "\n",
    " :numref:`fig_gru_2`说明了应用重置门之后的计算流程。\n",
    "\n",
    "![在门控循环单元模型中计算候选隐状态](https://d2l.ai/_images/gru-2.svg)\n",
    ":label:`fig_gru_2`\n",
    "\n",
    "### 隐状态\n",
    "\n",
    "上述的计算结果只是候选隐状态，我们仍然需要结合更新门$\\mathbf{Z}_t$的效果。\n",
    "这一步确定新的隐状态$\\mathbf{H}_t \\in \\mathbb{R}^{n \\times h}$\n",
    "在多大程度上来自旧的状态$\\mathbf{H}_{t-1}$和\n",
    "新的候选状态$\\tilde{\\mathbf{H}}_t$。\n",
    "更新门$\\mathbf{Z}_t$仅需要在\n",
    "$\\mathbf{H}_{t-1}$和$\\tilde{\\mathbf{H}}_t$\n",
    "之间进行按元素的凸组合就可以实现这个目标。\n",
    "这就得出了门控循环单元的最终更新公式：\n",
    "\n",
    "$$\\mathbf{H}_t = \\mathbf{Z}_t \\odot \\mathbf{H}_{t-1}  + (1 - \\mathbf{Z}_t) \\odot \\tilde{\\mathbf{H}}_t.$$\n",
    "\n",
    "每当更新门$\\mathbf{Z}_t$接近$1$时，模型就倾向只保留旧状态。\n",
    "此时，来自$\\mathbf{X}_t$的信息基本上被忽略，\n",
    "从而有效地跳过了依赖链条中的时间步$t$。\n",
    "相反，当$\\mathbf{Z}_t$接近$0$时，\n",
    "新的隐状态$\\mathbf{H}_t$就会接近候选隐状态$\\tilde{\\mathbf{H}}_t$。\n",
    "这些设计可以帮助我们处理循环神经网络中的梯度消失问题，\n",
    "并更好地捕获时间步距离很长的序列的依赖关系。\n",
    "例如，如果整个子序列的所有时间步的更新门都接近于$1$，\n",
    "则无论序列的长度如何，在序列起始时间步的旧隐状态都将很容易保留并传递到序列结束。\n",
    "\n",
    " :numref:`fig_gru_3`说明了更新门起作用后的计算流。\n",
    "\n",
    "![计算门控循环单元模型中的隐状态](https://d2l.ai/_images/gru-3.svg)\n",
    ":label:`fig_gru_3`\n",
    "\n",
    "总之，门控循环单元具有以下两个显著特征：\n",
    "\n",
    "* 重置门有助于捕获序列中的短期依赖关系。\n",
    "* 更新门有助于捕获序列中的长期依赖关系。\n",
    "\n",
    "## 从零开始实现\n",
    "\n",
    "为了更好地理解门控循环单元模型，我们从零开始实现它。\n",
    "首先，我们读取 :numref:`sec_rnn_scratch`中使用的时间机器数据集：\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "%load ../utils/djl-imports\n",
    "%load ../utils/plot-utils\n",
    "%load ../utils/Functions.java\n",
    "%load ../utils/PlotUtils.java\n",
    "\n",
    "%load ../utils/StopWatch.java\n",
    "%load ../utils/Accumulator.java\n",
    "%load ../utils/Animator.java\n",
    "%load ../utils/Training.java\n",
    "%load ../utils/timemachine/Vocab.java\n",
    "%load ../utils/timemachine/RNNModel.java\n",
    "%load ../utils/timemachine/RNNModelScratch.java\n",
    "%load ../utils/timemachine/TimeMachine.java\n",
    "%load ../utils/timemachine/TimeMachineDataset.java"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "NDManager manager = NDManager.newBaseManager();"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "int batchSize = 32;\n",
    "int numSteps = 35;\n",
    "\n",
    "TimeMachineDataset dataset =\n",
    "        new TimeMachineDataset.Builder()\n",
    "                .setManager(manager)\n",
    "                .setMaxTokens(10000)\n",
    "                .setSampling(batchSize, false)\n",
    "                .setSteps(numSteps)\n",
    "                .build();\n",
    "dataset.prepare();\n",
    "Vocab vocab = dataset.getVocab();"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 初始化模型参数\n",
    "\n",
    "下一步是初始化模型参数。\n",
    "我们从标准差为$0.01$的高斯分布中提取权重，\n",
    "并将偏置项设为$0$，超参数`numHiddens`定义隐藏单元的数量，\n",
    "实例化与更新门、重置门、候选隐状态和输出层相关的所有权重和偏置。\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "public static NDArray normal(Shape shape, Device device) {\n",
    "    return manager.randomNormal(0, 0.01f, shape, DataType.FLOAT32, device);\n",
    "}\n",
    "\n",
    "public static NDList three(int numInputs, int numHiddens, Device device) {\n",
    "    return new NDList(\n",
    "            normal(new Shape(numInputs, numHiddens), device),\n",
    "            normal(new Shape(numHiddens, numHiddens), device),\n",
    "            manager.zeros(new Shape(numHiddens), DataType.FLOAT32, device));\n",
    "}\n",
    "\n",
    "public static NDList getParams(int vocabSize, int numHiddens, Device device) {\n",
    "    int numInputs = vocabSize;\n",
    "    int numOutputs = vocabSize;\n",
    "\n",
    "    // Update gate parameters\n",
    "    NDList temp = three(numInputs, numHiddens, device);\n",
    "    NDArray W_xz = temp.get(0);\n",
    "    NDArray W_hz = temp.get(1);\n",
    "    NDArray b_z = temp.get(2);\n",
    "\n",
    "    // Reset gate parameters\n",
    "    temp = three(numInputs, numHiddens, device);\n",
    "    NDArray W_xr = temp.get(0);\n",
    "    NDArray W_hr = temp.get(1);\n",
    "    NDArray b_r = temp.get(2);\n",
    "\n",
    "    // Candidate hidden state parameters\n",
    "    temp = three(numInputs, numHiddens, device);\n",
    "    NDArray W_xh = temp.get(0);\n",
    "    NDArray W_hh = temp.get(1);\n",
    "    NDArray b_h = temp.get(2);\n",
    "\n",
    "    // Output layer parameters\n",
    "    NDArray W_hq = normal(new Shape(numHiddens, numOutputs), device);\n",
    "    NDArray b_q = manager.zeros(new Shape(numOutputs), DataType.FLOAT32, device);\n",
    "\n",
    "    // Attach gradients\n",
    "    NDList params = new NDList(W_xz, W_hz, b_z, W_xr, W_hr, b_r, W_xh, W_hh, b_h, W_hq, b_q);\n",
    "    for (NDArray param : params) {\n",
    "        param.setRequiresGradient(true);\n",
    "    }\n",
    "    return params;\n",
    "}"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 定义模型\n",
    "\n",
    "现在我们将定义隐状态的初始化函数 `initGruState()`。\n",
    "与 :numref:`sec_rnn_scratch`中定义的`initRnnState()`函数一样，\n",
    "此函数返回一个形状为（批量大小，隐藏单元个数）的 NDArray，NDArray 的值全部为零。\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "public static NDList initGruState(int batchSize, int numHiddens, Device device) {\n",
    "    return new NDList(manager.zeros(new Shape(batchSize, numHiddens), DataType.FLOAT32, device));\n",
    "}"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "现在我们准备定义门控循环单元模型，\n",
    "模型的架构与基本的循环神经网络单元是相同的，\n",
    "只是权重更新公式更为复杂。\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "public static Pair<NDArray, NDList> gru(NDArray inputs, NDList state, NDList params) {\n",
    "    NDArray W_xz = params.get(0);\n",
    "    NDArray W_hz = params.get(1);\n",
    "    NDArray b_z = params.get(2);\n",
    "\n",
    "    NDArray W_xr = params.get(3);\n",
    "    NDArray W_hr = params.get(4);\n",
    "    NDArray b_r = params.get(5);\n",
    "\n",
    "    NDArray W_xh = params.get(6);\n",
    "    NDArray W_hh = params.get(7);\n",
    "    NDArray b_h = params.get(8);\n",
    "\n",
    "    NDArray W_hq = params.get(9);\n",
    "    NDArray b_q  = params.get(10);\n",
    "\n",
    "    NDArray H = state.get(0);\n",
    "    NDList outputs = new NDList();\n",
    "    NDArray X, Y, Z, R, H_tilda;\n",
    "    for (int i = 0; i < inputs.size(0); i++) {\n",
    "        X = inputs.get(i);\n",
    "        Z = Activation.sigmoid(X.dot(W_xz).add(H.dot(W_hz).add(b_z)));\n",
    "        R = Activation.sigmoid(X.dot(W_xr).add(H.dot(W_hr).add(b_r)));\n",
    "        H_tilda = Activation.tanh(X.dot(W_xh).add(R.mul(H).dot(W_hh).add(b_h)));\n",
    "        H = Z.mul(H).add(Z.mul(-1).add(1).mul(H_tilda));\n",
    "        Y = H.dot(W_hq).add(b_q);\n",
    "        outputs.add(Y);\n",
    "    }\n",
    "    return new Pair(outputs.size() > 1 ? NDArrays.concat(outputs) : outputs.get(0), new NDList(H));\n",
    "}"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 训练与预测\n",
    "\n",
    "训练和预测的工作方式与 :numref:`sec_rnn_scratch`完全相同。\n",
    "训练结束后，我们分别打印输出训练集的困惑度，\n",
    "以及前缀“time traveler”和“traveler”的预测序列上的困惑度。\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "int vocabSize = vocab.length();\n",
    "int numHiddens = 256;\n",
    "Device device = manager.getDevice();\n",
    "int numEpochs = Integer.getInteger(\"MAX_EPOCH\", 500);\n",
    "\n",
    "int lr = 1;\n",
    "\n",
    "Functions.TriFunction<Integer, Integer, Device, NDList> getParamsFn = (a, b, c) -> getParams(a, b, c);\n",
    "Functions.TriFunction<Integer, Integer, Device, NDList> initGruStateFn =\n",
    "        (a, b, c) -> initGruState(a, b, c);\n",
    "Functions.TriFunction<NDArray, NDList, NDList, Pair<NDArray, NDList>> gruFn = (a, b, c) -> gru(a, b, c);\n",
    "\n",
    "RNNModelScratch model =\n",
    "        new RNNModelScratch(vocabSize, numHiddens, device,\n",
    "                getParamsFn, initGruStateFn, gruFn);\n",
    "TimeMachine.trainCh8(model, dataset, vocab, lr, numEpochs, device, false, manager);"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 简洁实现\n",
    "\n",
    "高级API包含了前文介绍的所有配置细节，\n",
    "所以我们可以直接实例化门控循环单元模型。\n",
    "这段代码的运行速度要快得多，\n",
    "因为它使用的是编译好的运算符而不是单个的 NDArray 运算来处理之前阐述的许多细节。\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "GRU gruLayer = GRU.builder().setNumLayers(1)\n",
    "        .setStateSize(numHiddens).optReturnState(true).optBatchFirst(false).build();\n",
    "RNNModel modelConcise = new RNNModel(gruLayer,vocab.length());\n",
    "TimeMachine.trainCh8(modelConcise, dataset, vocab, lr, numEpochs, device, false, manager);"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 小结\n",
    "\n",
    "* 门控循环神经网络可以更好地捕获时间步距离很长的序列上的依赖关系。\n",
    "* 重置门有助于捕获序列中的短期依赖关系。\n",
    "* 更新门有助于捕获序列中的长期依赖关系。\n",
    "* 重置门打开时，门控循环单元包含基本循环神经网络；更新门打开时，门控循环单元可以跳过子序列。\n",
    "\n",
    "## 练习\n",
    "\n",
    "1. 假设我们只想使用时间步$t'$的输入来预测时间步$t > t'$的输出。对于每个时间步，重置门和更新门的最佳值是什么？\n",
    "1. 调整和分析超参数对运行时间、困惑度和输出顺序的影响。\n",
    "1. 比较`rnn.RNN`和`rnn.GRU`的不同实现对运行时间、困惑度和输出字符串的影响。\n",
    "1. 如果仅仅实现门控循环单元的一部分，例如，只有一个重置门或一个更新门会怎样？\n"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Java",
   "language": "java",
   "name": "java"
  },
  "language_info": {
   "codemirror_mode": "java",
   "file_extension": ".jshell",
   "mimetype": "text/x-java-source",
   "name": "Java",
   "pygments_lexer": "java",
   "version": "14.0.2+12"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
